package server;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @author Y1n
 * @date 2021/11/19 14:37
 * @decs
 **/
public class StaticResourceUtil {

    /**
     * @param
     * @return
     * @author Y1n
     * @date 2021/11/19 14:38
     * @description 获取静态资源的绝对路径
     */
    public static String getAbsolutePath(String path) {
        String absolutePath = StaticResourceUtil.class.getResource("/").getPath();
        return absolutePath.replaceAll("\\\\", "/") + path;
    }

    /**
     * @param
     * @return
     * @author Y1n
     * @date 2021/11/19 14:45
     * @description 读取静态资源文件 通过输出流输出
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {

        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        int resourceSize = count;
        // 先输出http 请求头
        outputStream.write(HttpPortocolUtil.getHttpHeaderSuccess(resourceSize).getBytes(StandardCharsets.UTF_8));

        // 读内容输出

        long written = 0; // 已经读取的内容
        int byteSize = 1024; // 计划每次缓存的长度
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            // 如果已经读的 加上 1024 大于 总 长度 说明 剩余的 内容不足一个1024数组
            if (written + byteSize > resourceSize){
                byteSize = (int )(resourceSize - written ); //
                 bytes = new byte[byteSize];
            }

            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written += byteSize;
        }

    }
}
